package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;

import bean.BlobBEAN;
import util.HibernateSessionUtil;

public class Test {
	public static void main(String[] args) {
//		Test.save();
		Test.load();
	}

	private static void save() {
		Session session = null;
		Transaction tran = null;

		try {
			session = HibernateSessionUtil.getSession();
			tran = session.beginTransaction();

			BlobBEAN blobBean = new BlobBEAN();
			blobBean.setBlobId(1);

			// Text类型
			StringBuffer str = new StringBuffer();
			for (int i = 0; i < 10000; i++) {
				str.append("abcabc");
			}
			blobBean.setContent(str.toString());

			// Image类型
			String path = "F:\\123.jpg";
			InputStream inputStream = new FileInputStream(new File(path));
			byte[] imaBytes = IOUtils.toByteArray(inputStream);
			blobBean.setImage(imaBytes);

			session.save(blobBean);

			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tran.rollback();
		} finally {
			HibernateSessionUtil.closeSession();
		}

	}

	private static void load() {
		
		Session session = null;
		Transaction tran = null;

		try {
			session = HibernateSessionUtil.getSession();
			tran = session.beginTransaction();

			BlobBEAN blob=(BlobBEAN)session.get(BlobBEAN.class, new Integer(1));
			System.out.println(blob.getName());
			
			//属性的延迟加载，加载任意一个大字段时，会加载所有的属性延迟字段。
			String content=blob.getContent();
			OutputStream out=new FileOutputStream(new File("F:\\123.txt"));
			IOUtils.write(content, out);
			
			out.flush();
			out.close();
			
			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tran.rollback();
		} finally {
			HibernateSessionUtil.closeSession();
		}

	}

}
